<?php


/**
 * 
 * 
 */

class Member_mdl extends CI_Model
{
	
	//表名
	const TBL_MEMBERS = 'tb_members';
	
	
	
	
	
	
	public function __construct()
	{
		parent::__construct();
	}
	
	
	/**
     * 获取单个用户信息
     * 
     * @access public
	 * @param int $uid 用户id
     * @return array - 用户信息
     */
	public function get_user_by_id($id)
	{
		$data = array();
		
		$this->db->select('*')->from(self::TBL_MEMBERS)->where('id', $id)->limit(1);
		$query = $this->db->get();
		if($query->num_rows() == 1)
		{
			$data = $query->row_array();
		}
		$query->free_result();
		
		return $data;
	}
	
	/**
	 * 获取会员信息
	 * @access public
	 * @param string txnikename
	 * @return array - 会员信息
	 */
	
	public function get_user_bu_txnikename($txnikename)
	{
		$data = array();
		$this->db->select('id,txemail,txnikename')->from(self::TBL_MEMBERS)->where('txnikename', $txnikename)->limit(1);
		$query = $this->db->get();
		if($query->num_rows() == 1)
		{
			$data = $query->row_array();
		}
		$query->free_result();
		
		return $data;
	}
	
	/**
    * 检查用户是否通过验证
    * 
    * @access public
	* @param string - $name 用户名
	* @param string - $password 密码
    * @return mixed - FALSE/uid
    */	
	public function validate_user($username, $password)
	{
		$data = FALSE;
		
		$this->db->where('txnikename', $username);
		$query = $this->db->get(self::TBL_MEMBERS);
		
		if($query->num_rows() == 1)
        {
            $data = $query->row_array();
        }
      		
		if(!empty($data))
		{
			$data = (Common::hash_Validate($password, $data['txpassword'])) ? $data : FALSE;
		}
		
		$query->free_result();
		
		return $data;
	}
	
	/**
    * 修改用户信息
    * 
    * @access public
	* @param int - $uid 用户ID
	* @param int - $data 用户信息
	* @param int - $cipher_password 密码是否hash	
    * @return boolean - success/failure
    */	
	public function update_user($uid, $data, $hashed = TRUE)
	{
		if(!$hashed)
		{
		  $data['password'] = Common::do_hash($data['password']);
		}
		
		$this->db->where('id', intval($uid));
		$this->db->update(self::TBL_MEMBERS, $data);
		
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}
	
	/**
	 * 密码重置,生成token
	 * @param aray $user - 用户信息(txnikename,id)
	 * @return void
	 */
	
	public function set_reset_password($user)
	{
		$data['token'] = Common::do_hash('reset_'.$user['id'].time());
		$data['uid'] =   $user['id'];
		$data['txemail'] = $user['txemail'];
		$this->db->insert('tb_resetpassword', $data); 
		return ($this->db->affected_rows() > 0) ? $data : FALSE;
	}
}